package com.jzo2o.market.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.market.enums.ActivityStatusEnum;
import com.jzo2o.market.enums.CouponStatusEnum;
import com.jzo2o.market.mapper.ActivityMapper;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.dto.request.ActivityQueryForPageReqDTO;
import com.jzo2o.market.model.dto.request.ActivitySaveReqDTO;
import com.jzo2o.market.model.dto.response.ActivityInfoResDTO;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.market.service.ICouponWriteOffService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import com.jzo2o.market.model.domain.Coupon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import static com.jzo2o.market.enums.ActivityStatusEnum.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-09-16
 */
@Service
@Slf4j
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements IActivityService {

    private static final int MILLION = 1000000;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ICouponService couponService;

    @Resource
    private ICouponWriteOffService couponWriteOffService;

    /**
     * 保存优惠券活动，和修改共用一个接口
     *
     * @param dto
     */
    @Override
    public void add(ActivitySaveReqDTO dto) {
        // 如果dto的id为空，执行新增方法
        if (ObjectUtils.isEmpty(dto.getId())) {
            // 对象拷贝
            Activity activity = BeanUtils.toBean(dto, Activity.class);
            // 设置状态为待生效
            activity.setStatus(ActivityStatusEnum.NO_DISTRIBUTE.getStatus());
            save(activity);
        } else {
            // 执行修改方法
            Activity activity = BeanUtils.copyProperties(dto, Activity.class);
            updateById(activity);
        }
    }

    /**
     * 分页查询优惠券活动
     *
     * @param dto
     * @return
     */
    @Override
    public PageResult<ActivityInfoResDTO> findByPage(ActivityQueryForPageReqDTO dto) {
        return PageHelperUtils.selectPage(dto, new PageHelperUtils.QueryExecutor<ActivityInfoResDTO>() {
            @Override
            public List<ActivityInfoResDTO> query() {
                return baseMapper.selectByPage(dto.getId(), dto.getName(), dto.getStatus(), dto.getType());
            }
        });
    }

    /**
     * 根据id查询优惠券活动详情
     *
     * @param id
     * @return
     */
    @Override
    public ActivityInfoResDTO findById(Long id) {
        ActivityInfoResDTO activityInfoResDTO = baseMapper.findById(id);

        if (activityInfoResDTO == null) {
            log.info("id = {}, 优惠券活动不存在", id);
            throw new ForbiddenOperationException("优惠券活动不存在");
        }

        return activityInfoResDTO;
    }


    /**
     * 活动状态定时变更
     */
    @Override
    public void updateActivityStatus() {
        lambdaUpdate().set(Activity::getStatus, DISTRIBUTING.getStatus()).eq(Activity::getStatus, NO_DISTRIBUTE.getStatus()).le(Activity::getDistributeStartTime, LocalDateTime.now()).gt(Activity::getDistributeEndTime, LocalDateTime.now()).update();

        lambdaUpdate().set(Activity::getStatus, LOSE_EFFICACY.getStatus()).in(Activity::getStatus, Arrays.asList(NO_DISTRIBUTE.getStatus(), DISTRIBUTING.getStatus())).lt(Activity::getDistributeEndTime, LocalDateTime.now()).update();


    }

    @Override
    public void revoke(Long id) {
        //思路如下：根据传入的id选择活动，判断活动状态是否为待生效或进行中，是则将活动状态改为撤销，否则抛出异常
        // 1.根据id查询活动
        Activity activity = getById(id);
        if (activity == null) {
            log.info("id = {}, 优惠券活动不存在", id);
            throw new ForbiddenOperationException("优惠券活动不存在");
        }
        if (activity.getStatus() != NO_DISTRIBUTE.getStatus() && activity.getStatus() != DISTRIBUTING.getStatus()) {
            log.info("id = {}, 优惠券活动状态为{}，无法撤销", id, activity.getStatus());
            throw new ForbiddenOperationException("优惠券活动状态为" + activity.getStatus() + "，无法撤销");
        }
        //调用ActivityService将活动状态改为已撤销
        lambdaUpdate().set(Activity::getStatus, VOIDED.getStatus())
                .eq(Activity::getId, id)
                .update();
        //2.将该活动下的未使用的优惠券状态改为已作废
        couponService.lambdaUpdate().set(Coupon::getStatus, CouponStatusEnum.VOIDED.getStatus())
                .eq(Coupon::getActivityId, id)
                .eq(Coupon::getStatus, CouponStatusEnum.NO_USE.getStatus()
                ).update();

    }
}
